package com.adxon.data;

import com.adxon.MsgException;
import com.adxon.data.Base;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;

public class DataSet<T> implements Iterable<T>,Iterator<T>{
	public static void main(String[] args){
		Item e=new Item();
		DataSet<Item> s=new DataSet<Item>(e,null);
		for(Item i:s){
			System.out.print(i.getId());
			System.out.print(": ");
			System.out.print(i.getTime());
			System.out.print(": ");
			System.out.println(i.getText());
		}
	}

	protected String	bsk;
	protected Class<?>	cls;
	protected Base		nxt;
	private ResultSet	res;
	protected T			tmp;

	public DataSet(T template,String order){
		try{
			bsk=((Base)template).bsk;
			cls=template.getClass();
			tmp=template;
			((Base)template).col=new TreeMap<String,Object>();
			((Base)template).key=new TreeMap<String,Object>();
			((Base)template).commitExt();
			for(Entry<String,Object> e:((Base)template).col.entrySet()){
				Object v=e.getValue();
				if(v==null)
					continue;
				String c=v.getClass().getSimpleName();
				System.out.println(e.getKey()+'('+c+"): "+v);
			}
			String q="SELECT * FROM "+bsk;
			if(order!=null)
				q+=" ORDER BY "+order;
			PreparedStatement s=Base.connect().prepareStatement(q);
			res=s.executeQuery();
		}catch(MsgException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	protected void addFilter(String column,int value){
		if(value!=0)
			;
	}
	protected void addFilter(String column,long value){
		if(value!=0)
			;
	}
	protected void addFilter(String column, String value) {
		if(value!=null)
			;
	}
	public T getTemplate(){
		return tmp;
	}
	@Override
	public boolean hasNext(){
		//System.out.println("hasNext: "+nxt);
		if(nxt==null){
			try{
				while(res.next()){
					nxt=((Base)cls.newInstance()).update(res);
					return true;
				}
				nxt=null;
			}catch(MsgException e){
				e.printStackTrace();
			}catch(SQLException e){
				e.printStackTrace();
			}catch(IllegalAccessException e){
				e.printStackTrace();
			}catch(InstantiationException e){
				e.printStackTrace();
			}
		}else return true;
		return false;
	}
	@Override
	public Iterator<T> iterator(){
		return this;
	}
	@Override
	public T next(){
		@SuppressWarnings("unchecked")
		T r=(T)nxt;
		nxt=null;
		return r;
	}
	@Override
	public void remove(){
	}
}